const jwt = require("jsonwebtoken");
const unless = require("koa-unless");

const authMiddleware = async (ctx, next) => {
  const token = ctx.headers.authorization?.split(" ")[1];

  if (!token) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "未提供 token",
      success: false,
    };
    return;
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || "default_secret");
    ctx.state.user = decoded;
    await next();
  } catch (err) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "无效的 token",
      success: false,
    };
  }
};

authMiddleware.unless = unless;

module.exports = authMiddleware;